/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 * 输入：head = [1,2,3,4,5], left = 2, right = 4
输出：[1,4,3,2,5]
 */
const createListNode = arr => {
  function ListNode(val, next) {
    this.val = val === undefined ? 0 : val
    this.next = next === undefined ? null : next
  }
  let oldListNode = null
  for (let index = arr.length - 1; index > -1; index--) {
    const val = arr[index]
    const newListNode = new ListNode(val, oldListNode)
    oldListNode = newListNode
  }
  return oldListNode
}

var reverseBetween = function (head, left, right) {
  if (!head.next) {
    return head
  }
  if (left === right) {
    return head
  }
  const reverseArr = []
  let i = 0
  let newhead = head
  let firstHead = null
  let lastHead = null
  while (newhead) {
    i++
    if (i >= left && i <= right) {
      reverseArr.push(newhead)
      if (i === left && !firstHead && lastHead) {
        firstHead = lastHead
      }
    }
    lastHead = newhead
    newhead = newhead.next
  }
  let k = reverseArr.length - 1

  let j = k
  const lastNode = reverseArr[j].next
  while (j > 0) {
    reverseArr[j].next = reverseArr[j - 1]
    j--
  }

  reverseArr[0].next = lastNode
  firstHead && (firstHead.next = reverseArr[k])
  if (1 === left) {
    return reverseArr[k]
  }
  return head
}
console.log(reverseBetween(createListNode([1, 2, 3]), 1, 2))
